<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { PropType, reactive, ref } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { SysRoleDetailVo } from '@/api/system/role/SysRole/types'
import { isBlank } from '@/utils/StringUtils'
import { useBaseWriteView } from '@/base/views/BaseWriteView'
import { sysDictChooseListApi } from '@/api/system/dict/SysDict'
import { KeyLabelValueChildrenVo, KeyLabelValueVo } from '@/base/api/KeyLabelValueVo'
import {
  ElButton,
  ElCheckbox,
  ElCheckboxGroup,
  ElDrawer,
  ElMessage,
  ElText,
  ElTree
} from 'element-plus'
import { sysMenuChooseTitleCascadeApi } from '@/api/system/menu/SysMenu'
import { SysComponentSearchQo } from '@/api/system/component/SysComponent/types'
import {
  sysComponentGetByMenuIdApi,
  sysComponentPageApi
} from '@/api/system/component/SysComponent'
import { SysRoleComponentEditQo } from '@/api/system/role/SysRoleComponent/types'
import { sysRoleComponentSaveRoleRelApi } from '@/api/system/role/SysRoleComponent'
// [[ OnflowGenerator Range (- selectFunctionImport -) Start ]]

// [[ OnflowGenerator Range (- selectFunctionImport -) End ]]

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<SysRoleDetailVo>>,
    default: () => null
  },
  editType: {
    type: String,
    default: 'add'
  },
  editId: {
    type: Number,
    default: -1
  }
})
const isAdd = ref(props.editType === 'add')

const menuTree = ref<Array<KeyLabelValueChildrenVo>>([])
const menuTreeRef = ref<ComponentRef<typeof ElTree>>()

const { formRegister, submit, doWatch } = useBaseWriteView(
  props,
  (data) => {
    data.menuIds = menuTreeRef.value?.getCheckedKeys()
  },
  (currentRow) => {
    if (menuTreeRef.value) {
      menuTreeRef.value.setCheckedKeys(currentRow.menuIds)
    }
  }
)
doWatch()

const formRef = ref<typeof Form>()
// [[ OnflowGenerator Range (- dictFunctions -) Start ]]
const platformTypeOptions = ref<Array<KeyLabelValueVo>>([])
const getPlatformType = async () => {
  const res = await sysDictChooseListApi('platformType')
  platformTypeOptions.value = res.data
}
getPlatformType()

// [[ OnflowGenerator Range (- dictFunctions -) End ]]

const getMenuTree = async () => {
  const res = await sysMenuChooseTitleCascadeApi({
    excludeId: 0
  })
  menuTree.value = res.data
}
getMenuTree()

// [[ OnflowGenerator Range (- selectFunctions -) Start ]]

// [[ OnflowGenerator Range (- selectFunctions -) End ]]

const schema = reactive<FormSchema[]>([
  // [[ OnflowGenerator Range (- inputSchema -) Start ]]
  {
    field: 'name',
    label: '角色名',
    component: 'Input',
    componentProps: {
      placeholder: '请输入角色名',
      clearable: true
    }
  },
  {
    field: 'code',
    label: '角色编码',
    component: 'Input',
    componentProps: {
      placeholder: '请输入角色编码',
      clearable: true
    }
  },
  {
    field: 'platformType',
    label: '平台类型',
    value: 'onflow-backend',
    component: 'Select',
    componentProps: {
      placeholder: '请选择平台类型',
      clearable: true,
      filterable: true,
      options: platformTypeOptions
    }
  },
  {
    field: 'enable',
    label: '是否启用',
    value: true,
    component: 'Switch',
    componentProps: {
      placeholder: '请选择是否启用'
    }
  },
  {
    field: 'superAdmin',
    label: '是否为超级管理员角色',
    value: false,
    component: 'Switch',
    componentProps: {
      placeholder: '请选择是否为超级管理员角色'
    }
  },
  {
    field: 'remark',
    label: '备注',
    component: 'Input',
    componentProps: {
      placeholder: '请输入备注',
      clearable: true
    }
  },
  // [[ OnflowGenerator Range (- inputSchema -) End ]]
  {
    field: 'createTime',
    label: '创建时间',
    component: 'Input',
    remove: isAdd.value,
    componentProps: {
      placeholder: '暂无创建时间',
      disabled: true
    }
  },
  {
    field: 'updateTime',
    label: '更新时间',
    component: 'Input',
    remove: isAdd.value,
    componentProps: {
      placeholder: '暂无更新时间',
      disabled: true
    }
  },
  {
    field: 'createUserName',
    label: '创建人',
    component: 'Input',
    remove: isAdd.value,
    componentProps: {
      placeholder: '暂无创建人',
      disabled: true
    }
  },
  {
    field: 'updateUserName',
    label: '更新人',
    component: 'Input',
    remove: isAdd.value,
    componentProps: {
      placeholder: '暂无更新人',
      disabled: true
    }
  }
])

const rules = reactive({
  // [[ OnflowGenerator Range (- rules -) Start ]]
  name: [
    required(),
    {
      validator: (_, value, callback) => {
        if (isBlank(value)) {
          callback()
          return
        }
        if (value.length > 50) {
          callback(new Error('角色名不能超过50个字符'))
        } else {
          callback()
        }
      }
    }
  ],
  code: [
    required(),
    {
      validator: (_, value, callback) => {
        if (isBlank(value)) {
          callback()
          return
        }
        if (value.length > 100) {
          callback(new Error('角色编码不能超过100个字符'))
        } else {
          callback()
        }
      }
    }
  ],
  platformType: [
    required(),
    {
      validator: (_, value, callback) => {
        if (isBlank(value)) {
          callback()
          return
        }
        if (value.length > 100) {
          callback(new Error('平台类型不能超过100个字符'))
        } else {
          callback()
        }
      }
    }
  ],
  enable: [required()],
  superAdmin: [required()],
  remark: [
    {
      validator: (_, value, callback) => {
        if (isBlank(value)) {
          callback()
          return
        }
        if (value.length > 500) {
          callback(new Error('备注不能超过500个字符'))
        } else {
          callback()
        }
      }
    }
  ]
  // [[ OnflowGenerator Range (- rules -) End ]]
})

// 关联组件 开始
const drawerVisible = ref(false)
const componentList = ref<Array<KeyLabelValueVo>>([])
const checkList = ref<Array<string>>([])
const drawerMenuId = ref(0)

const chooseComponentPermission = async (nodeData) => {
  checkList.value = []
  componentList.value = []

  drawerVisible.value = true
  drawerMenuId.value = nodeData.key
  const request: SysComponentSearchQo = {
    menuId: nodeData.key,
    enable: true
  }
  const res = await sysComponentGetByMenuIdApi(request)
  componentList.value = res.data
  console.log('componentList.value', componentList.value)
  checkList.value = componentList.value.filter((item) => item.value).map((item) => item.key)
  console.log('checkList.value', checkList.value)
}

// 全选逻辑
const selectAll = () => {
  checkList.value = componentList.value.map((item) => item.key)
}

// 全不选逻辑
const selectNone = () => {
  checkList.value = []
}

const saveComponentRel = async () => {
  const request: SysRoleComponentEditQo = {
    menuId: drawerMenuId.value,
    roleId: props.editId,
    platformType: 'onflow-backend',
    componentIdList: checkList.value
  }
  const res = await sysRoleComponentSaveRoleRelApi(request)
  if (res.code === 200) {
    drawerVisible.value = false
    checkList.value = []
    componentList.value = []
    ElMessage.success('保存成功')
  }
}

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="schema" ref="formRef" />

  <div>
    <ElText type="primary" size="large" style="width: 100%">选择菜单权限</ElText>
    <ElTree show-checkbox :data="menuTree" ref="menuTreeRef" node-key="key">
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <span>{{ node.label }}</span>
          <ElButton
            v-if="data.children.length === 0"
            size="small"
            @click="chooseComponentPermission(data)"
          >点击关联组件
          </ElButton>
        </div>
      </template>
    </ElTree>
  </div>

  <ElDrawer v-model="drawerVisible" title="组件信息" direction="rtl" :size="'45%'">
    <div style="margin-bottom: 10px">
      <ElButton type="success" @click="selectAll">全选</ElButton>
      <ElButton type="default" @click="selectNone">全不选</ElButton>
    </div>
    <ElCheckboxGroup v-model="checkList">
      <ElCheckbox v-for="item in componentList" :key="item.key" :label="item.key">
        {{ item.label }}
      </ElCheckbox>
    </ElCheckboxGroup>
    <ElButton type="primary" @click="saveComponentRel" style="margin-top: 20px">保存</ElButton>
  </ElDrawer>
</template>

<style scoped lang="less">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
